<template>
    <div class="content">
      <div class="search-box">
        <div class="label">搜索</div>
        <el-input v-model="location" placeholder="请输入想查询的地址" id="tipinput"></el-input>
        <div class="route">
          <el-input v-model="from" placeholder="请输入起点" id="from"></el-input>
          <el-input v-model="to" placeholder="请输入终点" id="to"></el-input>
          <el-button type="primary" round @click="drivingplan">规划路线</el-button>
        </div>
      </div>
      <div id="map-container"></div>
      <div id="panel"></div>
    </div>
  </template>  
  <script>
  import AMapLoader from "@amap/amap-jsapi-loader";
  window._AMapSecurityConfig = {
    // 设置安全密钥
    securityJsCode: "75c29c7039dc0b07c0770e291418a351",
  };
  export default {
    data() {
      return {
      from:"",
      to:"",
      location: "", // input的内容
      map: null,// 
      lnglat: [], // 经纬度数组 [lng,lat] 
      auto: null,
      placeSearch: null,
      markers: [],
      driving: null,
      };
    },
    mounted() {
      this.initMap();
    },
    created() {
    //   调用两次将生成两个路线指导
    //   this.initMap();
    },
    methods: {
        initMap() {
            AMapLoader.reset()
            AMapLoader.load({
            // key: "cb188034b6def4f324d15fccd33ebf19", // 申请好的Web端开发者Key，首次调用 load 时必填
            key: "9ac3e72b68d6e4f4c4e21c9d196efec8", // 申请好的Web端开发者Key，首次调用 load 时必填
            version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
            plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Driving", "AMap.DragRoute"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
            })
            .then((AMap) => {
                console.log(AMap);
                this.map = new AMap.Map("map-container", {
                viewMode: "2D", //  是否为3D地图模式
                zoom: 13, // 初始化地图级别
                center: [112.991381, 28.139689], //中心点坐标
                resizeEnable: true,
                });
                this.map.on("click", this.clickMapHandler)
                // this.drivingMap()
                // this.drivingMap2()
                // this.mapDragRoute()
                this.searchMap()
                

            })
            .catch((e) => {
                console.log(e);
            });
        },
        // 点击地图事件获取经纬度，并添加标记
        clickMapHandler(e) {
            this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
            this.setMarker(this.lnglat);
        },
        //  添加标记
        setMarker(lnglat) {
            console.log("位置", lnglat); // lnglat=[经度,纬度]
            let marker = new AMap.Marker({
                position: lnglat,
            });
            marker.setMap(this.map);
            this.markers.push(marker); // 在data中记录标记点
        },
        // 删除之前后的标记点
        removeMarker() {
            // 判断是否存被标记的点，有--->移除
            if (this.markers) {
                this.map.remove(this.markers);
            }
        },
        // 地图关键字查询
        searchMap() {
        // 搜索框自动完成类
        this.auto = new AMap.AutoComplete({
            input: "tipinput",
        });
        //构造地点查询类
        this.placeSearch = new AMap.PlaceSearch({
            map: this.map,
        });
        // 当选中某条搜索记录时触发
        this.auto.on("select", this.selectSite);
        },
        //当选中某条搜索记录时触发
        selectSite(e) {
        this.lnglat = [e.poi.location.lng, e.poi.location.lat];
        this.placeSearch.setCity(e.poi.adcode);
        this.placeSearch.search(e.poi.name); 
        },
        
        // 测试用绘制初始路径
        // mapDragRoute() {
        // var path = [];
        // path.push([112.991381, 28.139689]);
        // path.push([113.941381, 28.129689]);
        // path.push([114.901381, 28.149689]);
        // this.mapDragRoute;
        // var route = new AMap.DragRoute(this.map, path, AMap.DrivingPolicy.LEAST_FEE); //构造拖拽导航类
        // route.search(); //查询导航路径并开启拖拽导航
        // console.log(22222)
        // },
        
        //途经点路线规划
        // drivingMap() {
        // var driving = new AMap.Driving({
        //     map: this.map,
        //     panel: "panel",
        // });
        //  // 根据起终点经纬度规划驾车导航路线
        // driving.search(
        // new AMap.LngLat(112.991381, 28.139689),
        // new AMap.LngLat(114.308783, 30.560878),
        // {
        // waypoints: [new AMap.LngLat(114.317433, 30.55351)],
        // },
        // function (status, result) {
        // // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
        // if (status === "complete") {
        //     console.log("绘制驾车路线完成");
        // } else {
        //     console.log("获取驾车数据失败：" + result);
        // }
        // });
        // },
        
        drivingplan(){
            var start = this.from
            var end = this.to
            console.log(start,end)
            this.drivingMapPanle(start,end)
        },

        //构造路线导航类，据起终点经纬度规划驾车导航路线
        drivingMapPanle(start,end) {
        document.getElementById("panel").innerHTML = "";
        //  配置参数
        var drivingOption = {
            policy: AMap.DrivingPolicy.LEAST_TIME, // 其它policy参数请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingPolicy
            ferry: 1, // 是否可以使用轮渡
            province: "湘", // 车牌省份的汉字缩写
            map: this.map,
            panel: "panel", // 绑定容器 id
        };
        // 构造路线导航类
        if(this.driving){
            this.driving.clear()
        }
        this.driving  = new AMap.Driving(drivingOption);
        // 根据起终点经纬度规划驾车导航路线
        // var start = new AMap.LngLat(116.379028, 39.865042)
        // var end = new AMap.LngLat(116.427281, 39.903719)
        this.driving.search(
          // start , end , 
          // [{keyword: '北京市地震局(公交站)'},
          //  {keyword: '亦庄文化园(地铁站)'}],
          [{keyword: start},
           {keyword: end}],
          function (status, result) {
            if (status === "complete") {
            console.log("绘制驾车路线完成");
            } else {
            console.log("获取驾车数据失败：" + result);
            }
        });
        },
        
        // 规划结果 + 驾车路线绘制(复杂版)
        // drivingMap2() {
        // let that = this;
        // var driving = new AMap.Driving({
        //     // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式,还有其他几种方式见Api文档
        //     policy: AMap.DrivingPolicy.LEAST_TIME,
        // });
        // //起、终点
        // var start_xy = new AMap.LngLat(116.379028, 39.865042); // 起点的经纬度
        // var end_xy = new AMap.LngLat(116.427281, 39.903719); // 终点的经纬度
        // // 根据起终点经纬度规划驾车导航路线
        // driving.search(start_xy, end_xy, function (status, result) {
        //     console.log(start_xy, end_xy, status, result);
        //     if (status === "complete") {
        //     if (result.routes && result.routes.length) {
        //         console.log(result.routes[0]);
        //         // 绘制第一条路线，也可以按需求绘制其它几条路线
        //         var path = that.parseRouteToPath(result.routes[0]);
        //         var startMarker = new AMap.Marker({
        //         position: path[0],
        //         icon: "https://webapi.amap.com/theme/v1.3/markers/n/start.png",
        //         map: that.map,
        //         });
        //         var endMarker = new AMap.Marker({
        //         position: path[path.length - 1],
        //         icon: "https://webapi.amap.com/theme/v1.3/markers/n/end.png",
        //         map: that.map,
        //         });
        //         var routeLine = new AMap.Polyline({
        //         path: path,
        //         isOutline: true,
        //         outlineColor: "#ffeeee",
        //         borderWeight: 2,
        //         strokeWeight: 5,
        //         strokeColor: "#0091ff",
        //         lineJoin: "round",
        //         });
        //         routeLine.setMap(that.map);
        //         // 调整视野达到最佳显示区域
        //         that.map.setFitView([startMarker, endMarker, routeLine]);
        //         console.log("绘制驾车路线完成");
        //     }
        //     } else {
        //     console.log("获取驾车数据失败：" + result);
        //     }
        // });
        // },



    },
  };
  </script>
  
  <style  scoped>
  .search-box {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    height: 50px;
    width : 1200px;
    .label {
      width: 100px;
      text-align: center;
      
    }
  }
  .content {
    position: relative;
  }
  #panel {
    position: absolute;
    width: 200px;
    height: 100px;
    top: 50px;
    right: 20px;
    z-index: 2;
  }
  #map-container {
    overflow: hidden;
    width: 100%;
    height: 800px;
    margin: 0;
  }
  .route {
    display: flex;
    margin-left: 200px;
    
  }
  #tipinput {
      width: 100px;
      margin-right: 200px;
    }

  </style>
 
  